<?php
/**
 * Created by PhpStorm.
 * User: zc
 * Date: 2019/8/4
 * Time: 15:19
 */
namespace app\common\logic;

use addons\adszone\library\Adszone;
use app\admin\controller\Zlog;
use app\common\library\EvaluationManager;
use think\Db;
use think\Exception;

class PersonalM
{
    private $user_id = 0;
    private $org_cate_id = 0;
    private $user_type = 0;
    private $page = 1;
    private $pagesize = 15;
    private $status = 0;

    /*
     * 获取我的问答列表
     * @return array
     */
    public function getAskList()
    {
        if($this->user_id <= 0){
            return array();
        }
        $data = Db::table('edu_parent_questions q')
            ->join('edu_user u', 'q.user_id = u.id', 'left')
            ->where('q.user_id', '=', $this->user_id)
            ->where('q.org_cate_id', '=', $this->org_cate_id)
            ->field('q.*, u.username')
            ->order('q.createtime', 'desc')
            ->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if(isset($data['data']) && !empty($data['data'])){
            foreach ($data['data'] as &$val){
                $val['createtime'] = date('Y-m-d', $val['createtime']);
                $ans = $this->getAnswer($val['id']);
                $val['ansnum'] = isset($ans['total'])?$ans['total']:0;
                $val['answer'] = isset($ans['answer'])?$ans['answer']:array();
            }
        }
        return $data;
    }
    /*
     * 根据问答编号获取回答内容
     */
    public function getAnswer($questions_id)
    {
        if($questions_id <= 0){
            return array();
        }
        $total = Db::table('edu_parent_answers')->where('parent_questions_id', '=', $questions_id)->count();
        if($total <= 0){
            return array();
        }
        $ans = Db::table('edu_parent_answers')->where('parent_questions_id', '=', $questions_id)->field('*')->order('createtime')->limit(1)->find();
        $ans['createtime'] = date('Y-m-d', $ans['createtime']);

        return array('answer'=>$ans, 'total'=>$total);
    }

    /*
     * 获取我的测评列表
     */
    public function getEvaluationList()
    {
        if($this->user_id <= 0){
            return array();
        }
        $e = new EvaluationManager();
        $data = Db::table('edu_evaluation_order eo')
            ->join('edu_evaluation e', 'eo.evalutation_id = e.id', 'left')
            ->where('eo.user_id', '=', $this->user_id)
            ->where('eo.org_cate_id', '=', $this->org_cate_id)
            ->where('eo.type', '=', 1)
            ->field('eo.id as eorder_id,eo.name as eoname,eo.order_sn,eo.sex,eo.role,eo.birthday,eo.height,eo.weight,e.*')
            ->order('eo.id', 'desc')
            ->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if(isset($data['data']) && !empty($data['data'])){
            $pic = new Adszone();
            $images = $pic->getAdsByMark('ceping_img',ORG_CATE_ID);
            foreach($data['data'] as &$val){
                {
                    $val['hasinfo'] = 1;
                    if($val['tag'] == '父母问卷'){
                        $val['is_parent'] = 2;
                        if(empty($val['eoname']) || empty($val['sex']) || empty($val['role']) || empty($val['birthday'])){
                            $val['hasinfo'] = 2;
                        }
                    }else{
                        $val['is_parent'] = 1;
                        if(empty($val['eoname']) || empty($val['sex']) || empty($val['height']) || empty($val['weight']) || empty($val['birthday'])){
                            $val['hasinfo'] = 2;
                        }
                    }
                    if(empty($val['image'])){
                        $val['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
                    }
                    $res = $e->detail($val['order_sn']);
                    $val['status'] = isset($res['status'])?$res['status']:-1;
                }
            }
        }
        return $data;
    }
    /*
     * 获取我的咨询列表
     */
    public function getConsultList($type = 1)
    {
        if($this->user_id <= 0){
            return array();
        }
        $column = ($type== 2) ? 'c.teacher_id' : 'c.user_id';//老师展示被指定的咨询
        $data = Db::table('edu_consult_reply c')
//            ->join('edu_learn_cate_teacher t', 'c.teacher_id = t.id', 'left')
            ->join('edu_consult_room r', 'c.consult_room_id = r.id', 'left')
            ->where($column, '=', $this->user_id)
//            ->where('c.type', '<>', 4)
            ->field('c.id,c.introduce,c.createtime,c.start_time,c.ent_time,c.consult_room_id,c.room_id,c.type,c.teacher_name,c.teacher_phone,c.teacher_id,r.image')->order('c.createtime', 'asc')
            ->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if(isset($data['data']) && !empty($data['data'])){
            foreach ($data['data'] as &$val){
                if(is_null($val['start_time']) || empty($val['start_time'])){
                    $val['wait_time'] = $this->getWaitTime($val['createtime']);
                }else{
                    $val['wait_time'] = '';
                }
                if($val['start_time'] <= 0){
                    $val['start_time'] = date('Y年m月d日 H:i', $val['createtime']);
                }else{
                    $val['start_time'] = date('Y年m月d日 H:i', $val['start_time']);
                }
                $val['isclose'] = $val['ent_time']>0?true:false;
                $val['ent_time'] = date('Y年m月d日 H:i', $val['ent_time']);
            }
        }
        return $data;
    }

    /**
     * @param $time
     * @return string
     */
    public function getWaitTime($time)
    {
        $waittime = time()-$time;
        $second = $waittime%60;
        $str = $second.'秒';
        $minute = ($waittime - $second)/60%60;
        if($minute > 0){
            $str = $minute.'分钟'.$str;
            $hour = (($waittime - $second)/60 - $minute)/60%24;
            if($hour > 0){
                $str = $hour.'小时'.$str;
                $days = ((($waittime - $second)/60 - $minute)/60 - $hour)/24;
                if($days > 0){
                    $str = $days.'天'.$str;
                }
            }
        }
        return $str;
    }

    /*
     * 根据id获取老师信息
     * @param $id
     */
    public function getTeacherInfo($id)
    {
        $data = Db::table('edu_learn_cate_teacher t')
            ->join('edu_user u', 't.user_id = u.id', 'left')
            ->where('t.id', $id)->field("t.*,u.avatar")->find();
        return $data;
    }

    /*
     * 获取我的优惠券列表
     */
    public function getCouponList()
    {
        if($this->user_id <= 0){
            return array();
        }
        $query = Db::table('edu_coupon c')
            ->join('edu_coupon_user cu', 'c.id = cu.coupon_id', 'left')
            ->field('c.*,cu.status')
            ->where('cu.user_id', '=', $this->user_id)
            ->where('cu.org_cate_id', '=', $this->org_cate_id);
        if($this->status > 0){
            $query = $query->where('cu.status', '=', $this->status);
        }
        $data = $query->order('cu.create_time', 'desc')->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if(isset($data['data']) && !empty($data['data'])){
            foreach ($data['data'] as &$val){
                $val['start_time'] = date('Y-m-d', $val['start_time']);
                $val['end_time'] = date('Y-m-d', $val['end_time']);
            }
        }
        return $data;
    }

    /*
    * 获取我的课程列表
    */
    public function getCourseList()
    {
        if($this->user_id <= 0){
            return array();
        }
        $data = Db::table('edu_learn_course_order o')
            ->join('edu_learn_course c', 'o.learn_course_id = c.id', 'left')
            ->field('c.id,c.name,c.introduce,c.buy_numbers,c.image,c.thumbs,c.content,c.is_system')
            ->where('o.user_id', '=', $this->user_id)
            ->where('o.org_cate_id', '=', $this->org_cate_id)
            ->order('o.createtime', 'desc')->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if($data){
            $pic = new Adszone();
            $images = $pic->getAdsByMark('course_img',ORG_CATE_ID);
            foreach ($data as &$val){
                if($val['is_system'] == 1){
                    $val['chapters'] = 1;
                }else{
                    $val['chapters'] = Db::name('learn_course_system')->where(['sys_id'=> $val['id']])->count();
                }
                if (empty($val['image'])) {
                    $val['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
                }
            }
        }
        return $data;
    }

    /*
    * 获取我的积分列表
    */
    public function getScoreList()
    {
        if($this->user_id <= 0){
            return array();
        }
        $data = Db::table('edu_user')->field('id,username,nickname,avatar,score')
            ->where('org_cate_id', '=', $this->org_cate_id)
            ->where('user_type', '<>', 2)
            ->order('score', 'desc')
            ->order('id', 'asc')
            ->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if($this->page == 1){
            $sql = 'SELECT b.id,b.username,b.nickname,b.avatar,b.score,b.rownum as sort FROM (SELECT t.*, @rownum := @rownum + 1 AS rownum FROM (SELECT @rownum := 0) r,(SELECT * FROM edu_user WHERE org_cate_id = '.$this->org_cate_id.' AND user_type != 2 ORDER BY score DESC,id ASC ) AS t ) AS b WHERE b.id = '.$this->user_id;
            $data['info'] =Db::query($sql);
        }
        if(isset($data['data']) && !empty($data['data'])){
            foreach ($data['data'] as $key => &$val){
                $val['sort'] = ($this->page - 1)*$this->pagesize + $key + 1;
            }
        }
        return $data;
    }

    /*
    * 获取我的课程列表
    */
    public function getCourseHistoryList()
    {
        if($this->user_id <= 0){
            return array();
        }
        $data = Db::table('edu_learn_course_history h')
            ->join('edu_learn_course c', 'h.learn_course_id = c.id', 'left')
            ->field('c.id,c.name,c.buy_numbers,c.image,c.thumbs,c.content,h.last_view_time')
            ->where('h.user_id', '=', $this->user_id)
            ->order('h.last_view_time', 'desc')
            ->paginate($this->pagesize, false, ['page'=>$this->page])->toArray();
        if(isset($data['data']) && !empty($data['data'])){
            foreach ($data['data'] as &$val){
                $val['last_view_time'] = date('Y-m-d', $val['last_view_time']);
            }
        }
        return $data;
    }

    /*
     * 优惠券列表接口
     */
    public function getCoupon()
    {
        $data = Db::name('coupon')->alias('a')
            ->join('edu_coupon_user u', 'u.coupon_id = a.id', 'left')
            ->where('a.start_time', '<', time())
            ->where('a.end_time', '>', time())
            ->where('a.status', 1)
            ->where('a.got_time', '<', 'a.count')
            ->where('u.user_id <> '. $this->user_id.' or u.user_id  is null')
            ->group('a.id')
            ->field('a.*')->order('a.id', 'desc')->select();
        return $data;
    }

    /*
    * 优惠券列表接口
    */
    public function saveCoupon($data)
    {
        try{
            $res = Db::name('coupon_user')->insert($data);
            if($res){
                Db::name('coupon')->where(['id' => $data['coupon_id']])->setInc('got_time', 1);
            }
            return $res;
        }catch (Exception $e){
            return false;
        }

    }

    /*
   * 优惠券列表接口
   */
    public function couponinfo($id)
    {
        $data = Db::name('coupon')->where('id', $id)->field('*')->find();
        return $data;
    }

    /**
     * @param $user_id
     * @return $this
     */
    public function setUserId($user_id)
    {
        $this->user_id = $user_id;
        return $this;
    }

    /**
     * @return int
     */
    public function getUserId(){
        return $this->user_id;
    }

    public function setOrgCateId($org_cate_id)
    {
        $this->org_cate_id = $org_cate_id;
        return $this;
    }

    /**
     * @param $user_type
     * @return $this
     */
    public function setUserType($user_type)
    {
        $this->user_type = $user_type;
        return $this;
    }

    /**
     * @return int
     */
    public function getUserType(){
        return $this->user_type;
    }

    /**
     * @param $page
     * @return $this
     */
    public function setPage($page)
    {
        $this->page = abs($page) > 0?abs($page):1;
        return $this;
    }

    /**
     * @return int
     */
    public function getPage(){
        return $this->page;
    }

    /**
     * @param $pagesize
     * @return $this
     */
    public function setPagesize($pagesize)
    {
        $this->pagesize = abs($pagesize) > 0?abs($pagesize):15;
        return $this;
    }

    /**
     * @return int
     */
    public function getPagesize(){
        return $this->pagesize;
    }

    /**
     * @param $status
     * @return $this
     */
    public function setStatus($status)
    {
        $this->status = $status;
        return $this;
    }
}